import { resource, lyric, playListU } from '@/api/detail';
import { checkoutType } from '@/utils/optimize'

const state = {
  // 登录用户信息
  userInfo: {},
  // 侧边栏用户歌单
  userPlayList: [],
  // 首页推荐歌单
  resourceList: [],
  // 播放列表
  audioList: [],
  // 当前播放id
  audioId: {},
  // 存放歌词信息
  lyricObj: {}
}

const mutations = {
  USERINFO(state, value) {
    state.userInfo = value;
    // 登录后，将用户信息存起来避免刷新后丢失数据
    localStorage.setItem('userInfo', JSON.stringify(value));
  },
  RESOURCE(state, value) {
    console.log(value);
    state.resourceList = value;
  },
  // 播放列表
  AUDIOLIST(state, value) {
    state.audioList = value;
  },
  // 追加播放列表
  ADDAUDIOLIST(state, value) {
    console.log(state.audioList, value);
    let list = state.audioList;
    if (checkoutType(value) === 'Array') {
      // list = state.audioList.concat(value);
      list = list.concat(value);
    } else {
      // list = state.audioList.unshift(value)
      if (list && list.length) {
        const c = JSON.parse(localStorage.getItem('currentSong')).id;
        const playIndex = list.findIndex(item => item.id === c);
        if (playIndex !== -1) {
          // state.audioList.splice(playIndex + 1, 0, value);
          list.splice(playIndex + 1, 0, value);
        } else {
          list.unshift(value);
        }
      } else {
        list.push(value);
      }
      // state.audioList = list;
      // state.audioList.push(value);
      // list.push(value);
    }
    // 数组去重后重写给audioList赋值
    const newObj = {};
    state.audioList = list.reduce((preVal, curVal) => {
      newObj[curVal.id] ? '' : newObj[curVal.id] = preVal.push(curVal); 
      return preVal;
    }, []);
  },
  // 当前需要播放的歌曲id
  AUDIOID(state, id) {
    state.audioId = id;
  },
  // 歌词信息
  LYRIC(state, value) {
    state.lyricObj = value;
  },
  USERPLAYLIST(state, value) {
    console.log(value)
    state.userPlayList = value;
  }
}

const actions = {
  async getResource({commit}) {
    const res = await resource();
    commit('RESOURCE', res.data.recommend);
  },
  async getLyric({commit}, id) {
    const res = (await lyric(id)).data;
    commit('LYRIC', res);
  },
  async getPlayListU({ commit }, params) {
    const res = (await playListU(params)).data;
    // return res.data;
    console.log(res);
    commit('USERPLAYLIST', res.playlist);
  }
}

const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}